//
//  WBLoginController.swift
//  WeiboTen
//
//  Created by ItHeiMa on 2017/7/7.
//  Copyright © 2017年 itHeima. All rights reserved.
//

import UIKit

class WBLoginController: UIViewController {

    /// webView的懒加载属性
    lazy var webView: UIWebView = {
        let webView = UIWebView(frame: self.view.bounds)
        webView.delegate = self
        return webView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置UI
        setupUI()
    }
}

extension WBLoginController {
    func setupUI () {
        //设置背景颜色
        self.view.backgroundColor = UIColor.yellow
        
        //添加返回按钮
        let leftItem = UIBarButtonItem(title: "返回", style: .plain, target: self, action: #selector(back))
        self.navigationItem.leftBarButtonItem = leftItem
        
        //添加webView
        view.addSubview(webView)
        
        //加载登录页面
        loadLoginPage()
    }
    
    func loadLoginPage () {
        let urlStr = WBNetworkTool.shared.loginUrl
        let url = URL(string: urlStr)
        let reuqest = URLRequest(url: url!)
        
        webView.loadRequest(reuqest)
    }
}

extension WBLoginController {
    @objc func back () {
        dismiss(animated: true, completion: nil)
    }
}

extension WBLoginController: UIWebViewDelegate {
    
    /// 网页将要发起请求时调用
    ///
    /// - Parameters:
    ///   - webView: 当前的webView
    ///   - request: 当前发起的请求
    ///   - navigationType: 请求方式
    /// - Returns: bool值，true会发起请求，展示网页；如果false则不展示网页
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
        
        let url = request.url!
        let urlStr = (request.url?.absoluteString)!
        
        //如果url的主机是baidu，说明用户点击了授权或者是取消按钮
        if urlStr.hasPrefix(redirectURI) {
            //1. 如果用户点击的授权
            let query = url.query!
            
            if query.hasPrefix("code=") {
                let range = urlStr.range(of: "code=")!
                let endIndex = range.upperBound //取到的是range的右侧的index的值
                let code = urlStr.substring(from: endIndex)
                
                WBNetworkTool.shared.login(withCode: code) { (success) in
                    if success {
                        //登录成功之后发通知
                        let successNotification = Notification(name: loginSuccessNotificationName)
                        NotificationCenter.default.post(successNotification)
                        
                        self.dismiss(animated: true, completion: nil)
                    } else {
                        print("登录失败")
                    }
                }
                
            }
            //2. 如果用户点击的是取消按钮
            else {
                self.dismiss(animated: true, completion: nil)
            }
            
            return false
        }
        
        return true
    }
    
    
    /// 网页请求成功之后调用
    ///
    /// - Parameter webView: 当前的webView
    func webViewDidFinishLoad(_ webView: UIWebView) {
        //oc调用js的写法，参数是js的执行语句
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value='\(loginUserName)';document.getElementById('passwd').value='\(loginUserPassword)'");
    }
}
